import type { MavenArtifactDetail, MavenArtifactInfo, MavenRepoInfo, MavenRepoSearchOptions } from "./types.ts";
import { message } from "ant-design-vue";
import path from "@/framework/util/path.ts";
import { showMessageAndPrint } from "@/framework/util/log.ts";

interface AliyunMavenResponse<T> {
  object: T;
  successful: boolean;
}

export async function listRepos(): Promise<MavenRepoInfo[]> {
  const resp = await native.http.getJson<AliyunMavenResponse<MavenRepoInfo[]>>("https://maven.aliyun.com/repo/list?_input_charset=utf-8", {
    referrer: "https://maven.aliyun.com/mvn/search",
  });
  return resp.data.object || [];
}

export async function searchMavenRepo(options: MavenRepoSearchOptions): Promise<MavenArtifactInfo[]> {
  let url: string;
  const search = new URLSearchParams("_input_charset=utf-8");
  search.append("repoId", options.repoId);
  if (options.queryType === "keyword") {
    url = `https://maven.aliyun.com/artifact/aliyunMaven/searchArtifactByWords?`;
    search.append("queryTerm", options.keyword || "");
  } else {
    url = `https://maven.aliyun.com/artifact/aliyunMaven/searchArtifactByGav?`;
    search.append("groupId", options.groupId || "");
    search.append("artifactId", options.artifactId || "");
    search.append("version", options.version || "");
  }
  url += search.toString();
  const resp = await native.http.getJson<AliyunMavenResponse<MavenArtifactInfo[]>>(url, { referrer: "https://maven.aliyun.com/mvn/search" });
  return resp.data.object || [];
}

export async function getMavenArtifactDetail(id: string, repoId: string): Promise<MavenArtifactDetail | null> {
  try {
    const url = `https://maven.aliyun.com/artifact/detail?id=${id}&repositoryId=${repoId}&_input_charset=utf-8`;
    const resp = await native.http.getJson<AliyunMavenResponse<MavenArtifactDetail>>(url, { referrer: "https://maven.aliyun.com/mvn/search" });
    if (resp.data.successful) {
      return resp.data.object;
    }
    message.error("获取文件详情失败");
    return null;
  } catch (e) {
    showMessageAndPrint(e);
    return null;
  }
}

export async function getMavenArtifactDownloadUrl(id: string, repoId: string): Promise<string> {
  const url = `https://maven.aliyun.com/artifact/download/url?id=${id}&repositoryId=${repoId}&_input_charset=utf-8`;
  const resp = await native.http.getJson<AliyunMavenResponse<string>>(url, { referrer: "https://maven.aliyun.com/mvn/search" });
  return resp.data.object;
}

export const downloadArtifact = async (item: MavenArtifactInfo) => {
  try {
    const downloadUrl = await getMavenArtifactDownloadUrl(item.id, item.repositoryId);
    if (!downloadUrl) {
      message.error("下载地址获取失败");
      return;
    }

    const extname = path.extname(item.fileName);
    native.dialog
      .showSaveDialog({
        defaultPath: item.fileName,
        title: "选择下载路径",
        filters: extname ? [{ name: extname, extensions: [extname.substring(1)] }] : undefined,
      })
      .then(async ret => {
        if (!ret.canceled) {
          const result = await native.http.download({
            id: item.id,
            url: downloadUrl,
            savePath: ret.filePath,
          });
          message.success(`下载完成: ${result.filePath}`);
        }
      })
      .catch(showMessageAndPrint);
  } catch (e) {
    showMessageAndPrint(e);
  }
};
